package com.hxs.colorfultest2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.config.BeanIds;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyCustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @PostConstruct
    public void init() {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setDefaultTargetUrl("/index");

        setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
        setAuthenticationSuccessHandler(successHandler);
        setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        // 只接受POST方式传递的数据
        if (!"POST".equals(request.getMethod()))
            throw new AuthenticationServiceException("不支持非POST方式的请求!");
        // 验证码验证
        String captchaId = (String) request.getSession().getAttribute("vrifyCode");
        String parameter = request.getParameter("vrifyCode");
        if (StringUtils.isEmpty(captchaId))
            throw new AuthenticationServiceException("验证码不能为空!");
        if (!parameter.toLowerCase().equals(captchaId.toLowerCase())) {
            throw new AuthenticationServiceException("验证码错误!");
        }
        return super.attemptAuthentication(request, response);
    }

    @Override
    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

}
